<title>分类管理</title>

<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>商品分类</cite></a>
  </div>
</div>

<div class="layui-fluid ">
  <div class="layui-card">
    <div class="layui-card-header" style="text-align: right">
        <button class="layui-btn layui-btn-primary layui-btn-sm btn-add">新增分类</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" layadmin-event="refresh">刷新</button>
    </div>
    <div class="layui-card-body">
         <table id="category" lay-filter="category"></table>
    </div>
  </div>
</div>

<script type="text/html" id="barTpl">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit"><i class="layui-icon">&#xe642;</i></a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del"><i class="layui-icon">&#xe640;</i></a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add"><i class="layui-icon">&#xe654;</i></a>
</script>

<script type="text/html" id="fromTpl">
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit"><i class="layui-icon">&#xe642;</i></a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del"><i class="layui-icon">&#xe640;</i></a>
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add"><i class="layui-icon">&#xe654;</i></a>
</script>
<script type="text/html" class="form-tpl">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form" action="" lay-filter="form-tpl" style="width:350px;">
                    <div class="layui-form-item">
                      <label class="layui-form-label">分类名称</label>
                      <div class="layui-input-block">
                        <input type="text" name="name" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                      </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">分类图片</label>
                        <div class="layui-input-block">
                            <div class="layui-upload">
                                <div class="layui-upload-list">
                                  <img class="layui-upload-img logo-img">
                                  <p id="demoText"></p>
                                </div>
                                <button type="button" class="layui-btn layui-btn-xs" id="btn-upload">上传图片</button>
                            </div> 
                        </div>
                    </div>
                    <input type="hidden" name="logo" class="logo-input">
                    <div class="layui-form-item">
                      <label class="layui-form-label">上级分类</label>
                      <div class="layui-input-block">
                        <input type="text" name="parent" placeholder="请输入" autocomplete="off" class="layui-input parent">
                      </div>
                    </div>
                     <div class="layui-form-item">
                      <label class="layui-form-label">排序</label>
                      <div class="layui-input-block">
                        <input type="text" name="sort" value="0" autocomplete="off" class="layui-input" lay-verify="number">
                      </div>
                      <div class="layui-input-block">
                          <div class="layui-form-mid layui-word-aux">数字范围为0~255，数字越小越靠前</div>
                      </div>
                    </div>

                    <button class="layui-btn layui-hide btn-submit" lay-filter="btn-submit" lay-submit="">立即提交</button>
                </form>
            </div>
        </div>
    </div>
    
</script>


<script type="text/javascript">
    layui.use(['admin', 'table', 'flow', 'treeGrid', 'upload', 'form'], function(){
        var $        = layui.$,
            admin    = layui.admin,
            table    = layui.table,
            flow     = layui.flow,
            treeGrid = layui.treeGrid,
            setter   = layui.setter,
            upload   = layui.upload,
            form     = layui.form,
            element  = layui.element,
            cols     = [[
                {title:'分类名称', field:'name'},
                {title:'分类logo', field:'logo', templet: function(d){
                    return '<img class="avatar" style="width:100%" lay-src="' + setter.IMG_DOMAIN + d.logo + '">';
                }},
                {title:'排序', field:'sort'},
                {title:'操作', toolbar:"#barTpl"}
            ]],
            toolFun  = {},
            rows     = {},
            current  = 0;

        toolFun = {
          openTpl : function(title, done) {
              layer.open({
                  title: title,
                  type: 1,
                  shadeClose: true,
                  area: admin.screen() < 2 ? ['80%', '300px'] : ['600px', '500px'],
                  content: $('.form-tpl').html(),
                  btn : ['确认', '取消'],
                  yes: function(index, layero){
                      current = index;

                      layero.find('.btn-submit').click();

                      return false;
                  },
                  btn2: function(index) {
                     layer.close(index); 
                  },
                  success:function(layero, index){
                      current = index;

                      typeof done === 'function' && done(layero, index); 

                      toolFun.upload();  
                  }
              });
          },
          add: function(d) {
              toolFun.openTpl('新增分类', function(layero, index) {
                  layero.find('.layui-form').attr({
                      action : setter.host + 'goods/category',
                      method : 'post'
                  });

                  if (d) {
                     layero.find('input[name="parent"]').val(d.name);
                  }
              })
          },
          edit: function(obj, d) {
              toolFun.openTpl(d.name + '分类编辑', function(layero, index) {
                  layero.find('.layui-form').attr({
                      action : setter.host + 'goods/category/' + d.id,
                      method : 'put'
                  });
                  layero.find('input[name="name"]').val(d.name);
                  layero.find('input[name="logo"]').val(d.logo);
                  layero.find('input[name="sort"]').val(d.sort);
                  layero.find('.logo-img').attr('src', setter.IMG_DOMAIN + d.logo);

                  if (d.pid !== 0) {
                      layero.find('input[name="parent"]').val(rows[d.pid]);
                  }
              })
          },
          del: function(obj, d) {
              admin.req({
                  type:'delete',
                  url: setter.host + 'goods/category/' + d.id,
                  done : function(res){
                      layer.msg('删除成功', {offset: '15px', icon: 1, time: 1000}, function(){
                          obj.del();
                      });
                  }
              });
          },
          upload: function() {
              var uploadInst = upload.render({
                 elem: '#btn-upload',
                 url: setter.IMG_DOMAIN + 'api/upload',
                 before: function(obj){
                   obj.preview(function(index, file, result){
                     $('.logo-img').attr('src', result); //图片链接（base64）
                   });
                 },
                 done: function(res){
                      $('.logo-input').val(res.data);
                 },
                 error: function(){
                   var demoText = $('.upload-msg');

                   demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                   demoText.find('.demo-reload').on('click', function(){
                     uploadInst.upload();
                   });
                 }
              });
           }
        }

        // 渲染表格
        admin.req({
            url: setter.host + 'goods/category',
            done: function(res) {
                treeGrid.render({
                    elem: '#category',
                    data: res.data,
                    cols: cols,
                    treeId: 'id',
                    treeUpId: 'pid',
                    treeShowName : 'name',
                    done:function(d){
                        $.each(d.data, function(i, row){
                            rows[row.id] = row.name;
                        })
                        
                        flow.lazyimg({
                          elem: '.avatar'
                        });
                    }
                });
            }
        });

        // 新增分类
        $('.btn-add').click(function(){
            toolFun.add(null);
        });

        //监听工具条
        treeGrid.on('tool(category)', function(obj){ 
            var data     = obj.data,
                layEvent = obj.event,
                tr       = obj.tr;

            switch(layEvent) {
                case 'edit' :
                    toolFun.edit(obj, data);
                   
                    // obj.update({
                    //     username: '123',
                    //     title: 'xxx'
                    // });
                break;
                case 'del' :
                    layer.confirm('删除同时会把关联层级的数据都删除', function(index){
                        toolFun.del(obj, data);
                        layer.close(index);
                    });
                break;
                case 'add' :
                    toolFun.add(data);
                break;
            }
        });

        // 表单提交
        form.on('submit(btn-submit)', function(data){
            var post = data.field,
                elem = $(data.form);

            admin.req({
                type: elem.attr('method'),
                url: elem.attr('action'),
                data: post,
                done : function(res){
                    layer.msg('提交成功', {offset: '15px', icon: 1, time: 1000}, function(){
                        layer.close(current);
                        layui.index.render();
                    });
                }
            });

            return false;
        });
    })
</script>